package com.echo.servlet.ArticleServlet;

import com.echo.entity.Article;
import com.echo.entity.User;
import com.echo.service.ArticleService;
import com.echo.servlet.BaseServlet;
import com.echo.util.SessionUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 我的文章Servlet：处理/article-show请求（GET）
 * 用于展示当前登录用户发布的所有文章
 */
@WebServlet({"/article-show", "/echo-network/article-show"})
public class ArticleShowServlet extends BaseServlet {
    private final ArticleService articleService = new ArticleService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码
        setRequestEncoding(request);

        // 校验登录状态（未登录则重定向到登录页）
        if (!checkLogin(request, response)) {
            return;
        }

        // 获取当前登录用户
        User loginUser = SessionUtils.getCurrentUser(request);
        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/login.html");
            return;
        }

        try {
            // 查询当前用户发布的所有文章
            List<Article> articles = articleService.findByAuthorUsername(loginUser.getUsername());
            
            // 将文章列表存入请求域
            request.setAttribute("articles", articles);
            
            // 获取session中的成功提示信息（如果有）
            Object successMsg = request.getSession().getAttribute("successMsg");
            if (successMsg != null) {
                request.setAttribute("successMsg", successMsg);
                request.getSession().removeAttribute("successMsg"); // 移除session中的提示信息，避免重复显示
            }
            
            // 转发到我的文章页面
            forward(request, response, "/article-show.html");
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            request.setAttribute("errorMsg", "获取文章列表失败，请稍后再试");
            forward(request, response, "/article-show.html");
        }
    }
}